<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree
        :data="menuList"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        :default-checked-keys="menuIdCheckedArr"
        highlight-current
        :props="defaultProps"
      >
      </el-tree>
      <div class="buttons">
        <el-button @click="clearMenu">清空</el-button>
        <el-button type="primary" @click="saveMenu">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getMenuNodeList,
  getRoleMenuNodeList,
  allocRoleMenu
} from '@/service/menu'
export default {
  props: {
    id: {
      type: [Number, String],
      require: true,
      default: 1
    }
  },
  data () {
    return {
      // 菜单列表
      menuList: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      //   角色已有菜单权限数组
      menuIdCheckedArr: []
    }
  },
  created () {
    this.loadMenuNodeList()
  },
  methods: {
    async loadMenuNodeList () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menuList = data.data
        this.loadRoleMenu()
      }
    },
    // 获取角色菜单权限
    async loadRoleMenu () {
      console.log(this.id)
      const { data } = await getRoleMenuNodeList({ roleId: this.id })
      if (data.code === '000000') {
        this.handleRoleMenu(data.data)
        this.setCheckedKeys(this.menuIdCheckedArr)
      }
    },
    // 获取角色已有菜单权限
    handleRoleMenu (menus) {
      for (const menu of menus) {
        //   菜单被选中且没有子菜单
        if (menu.selected && menu.subMenuList === null) {
          this.menuIdCheckedArr.push(menu.id)
        }
        menu.subMenuList && this.handleRoleMenu(menu.subMenuList)
      }
      //   console.log(this.menuIdCheckedArr)
    },
    // 设置角色菜单权限
    setCheckedKeys (data) {
      this.$refs.tree.setCheckedKeys(data)
    },
    // 清空角色菜单列表
    clearMenu () {
      this.$refs.tree.setCheckedKeys([])
    },
    // 获取选中菜单
    async saveMenu () {
      //   console.log(this.$refs.tree.getCheckedKeys())
      const { data } = await allocRoleMenu({
        roleId: this.id,
        menuIdList: this.$refs.tree.getCheckedKeys()
      })
      if (data.code === '000000') {
        this.$message.success('菜单分配成功')
        this.$router.push({ name: 'role' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.buttons {
  margin-top: 30px;
  .el-button {
    margin-right: 16px;
  }
}
</style>
